chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
  if ((tab.url.indexOf("://localhost:9998/") > -1 || tab.url.indexOf("http://localhost:7778/") > -1 || tab.url.indexOf("://wms.ycimedia.net/") > -1|| tab.url.indexOf("http://localhost:9002/") > -1 ||tab.url.indexOf("http://127.0.0.1:5501/") > -1 || tab.url.indexOf("http://127.0.0.1:5501/") > -1|| tab.url.indexOf("://wms.mabangerp.com/") > -1|| tab.url.indexOf("://wms.private.mabangerp.com/") > -1)&&
      typeof changeInfo.url == 'undefined'){
      sendMessage("refresh", tab);
  }
});

function sendMessage(action, data) {
  chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
    chrome.tabs.sendMessage(tabs[0].id, { action, data }, (res) => {
      console.log("bg=>content", res);
    });
  });
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action && message.action === 'proxyApi') {
    sendRequest(message.url, message.params).then(res=>{
      sendResponse(res)
    }).catch(()=>{
      sendResponse()
    })
  }
})

function sendRequest(url, params) {
  return new Promise((resolve, reject)=>{
    var XHR = new XMLHttpRequest();
    // XHR.timeout = 2000;
    XHR.open("POST", url);
    XHR.setRequestHeader("content-type", "application/json");
    XHR.send(JSON.stringify(params));
    XHR.onreadystatechange = function () {
      // console.log(XHR.responseText)
      if (XHR.readyState == 4 && XHR.status == 200) {
        params.code = 1;
        resolve({ response : XHR.responseText, params })
        // sendMessage("api", { response : XHR.responseText, params });
        // document.getElementById("msg").innerHTML = "success";
      } else {
        params.code = 0;
        // reject({ response : XHR.responseText, params })
        // sendMessage("api", { response : XHR.responseText, params });
        // document.getElementById("msg").innerHTML = "fail";
      }
    }
  })
}
